--[[
	This file is part of FlexBar3.

	FlexBar3 is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	FlexBar3 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with FlexBar3.  If not, see <http://www.gnu.org/licenses/>.
]]

local Button = FlexBar3:GetModule("Button");
local SecureStateDriverFrame = Button.SecureStateDriverFrame;
local SpellClass = Button:NewButtonClass("AttributeSpell", 1);


function SpellClass:PlaceSpell(SpellName, SpellRank, StateModifier)
	-- If the spell is the highest rank available to the player, dont specify the rank, that way it'll autorank up when the user learns a new rank
	if(type(SpellRank) == "number") then
		-- Find out if the spell is the highest rank by requesting the texture of the spell one rank higher, if this isn't nil a rank above exists
		if(GetSpellTexture(("%s(%s %d)"):format(SpellName, RANK, SpellRank + 1)) ~= nil) then
			SpellName = ("%s(%s %d)"):format(SpellName, RANK, SpellRank);
		else
			SpellName = ("%s()"):format(SpellName);
		end
	else
		SpellName = ("%s()"):format(SpellName);
	end
	self:SetModifiedAttribute("type", "spell", StateModifier);
	self:SetModifiedAttribute("type-RightButton", "spell", StateModifier);
	self:SetModifiedAttribute("type-MiddleButton", "spell", StateModifier);
	self:SetModifiedAttribute("spell", SpellName, StateModifier);
	self:SetModifiedAttribute("spell-RightButton", SpellName, StateModifier);
	self:SetModifiedAttribute("spell-MiddleButton", SpellName, StateModifier);
	self:TriggerCallback("ActionChanged");
end

function SpellClass:DragSpellOff()
	local Spell = self:GetModifiedAttribute("spell");
	if(Spell and Spell ~= "") then
		self:PickupAction("spell", Spell);
		self:SetModifiedAttribute("type", nil);
		self:SetModifiedAttribute("spell", nil);
		local CurrentStateDB = self.StateDB[self:GetModifiedState()];
		CurrentStateDB.Type = nil;
		CurrentStateDB.SpellName = nil;
		CurrentStateDB.SpellRank = nil;
		self:TriggerCallback("ActionChanged");
	end
end

function SpellClass:RefreshSpellTexture()
	local Spell = self:GetModifiedAttribute("spell");
	if(Spell and Spell ~= "") then
		local SpellTexture = GetSpellTexture(Spell);
		if(SpellTexture) then
			self:SetTexture(SpellTexture);	
		else
			self:SetTexture([[Interface/Icons/INV_Misc_QuestionMark]]);
		end
	else
		self:SetTexture(nil);
	end
end
